package org.naxx.security.parser.datatype;

import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import org.naxx.security.datatype.DataType;
import org.naxx.security.parser.AbstractXmlParser;
import org.naxx.security.parser.util.QNames;

public class DataTypeParser extends AbstractXmlParser<List<DataType>> {

	/**
	 * Precondition: cursor points to opening DataTypes element. <br>
	 * Postcondition: cursor points to closing DataTypes element.
	 */
	public List<DataType> parse(XMLEventReader reader) throws Exception {
		List<DataType> result = new ArrayList<DataType>();
		XMLEvent event = reader.nextTag();
		while(event.isStartElement()) {
			StartElement start = event.asStartElement();
			Attribute idAttr = start.getAttributeByName(QNames.ID_ATTRIBUTE);
			Attribute isFunctionAttr = start.getAttributeByName(QNames.IS_FUNCTION_ATTRIBUTE);
			Attribute isGenericAttr = start.getAttributeByName(QNames.IS_GENERIC_ATTRIBUTE);
			Attribute isExtensionAttr = start.getAttributeByName(QNames.IS_EXTENSION_ATTRIBUTE);
			
			StringBuilder uriBuffer = new StringBuilder();
			event = reader.nextTag();
			event = this.getCharacters(reader, uriBuffer);
			
			StringBuilder nameBuffer = new StringBuilder();
			event = reader.nextTag();
			event = this.getCharacters(reader, nameBuffer);
			
			event = reader.nextTag();
			StringBuilder javaTypeNameBuffer = new StringBuilder();
			event = this.getCharacters(reader, javaTypeNameBuffer);
			event = reader.nextTag();
			event = reader.nextTag();
			
			DataType dataType = new DataType();
			dataType.setId(Integer.valueOf(idAttr.getValue()));
			dataType.setName(nameBuffer.toString());
			dataType.setUri(uriBuffer.toString());
			dataType.setJavaTypeName(javaTypeNameBuffer.toString().trim());
			if(isFunctionAttr != null) {
				dataType.setIsFunction(Boolean.valueOf(isFunctionAttr.getValue()));
			}
			if(isGenericAttr != null) {
				dataType.setIsGeneric(Boolean.valueOf(isGenericAttr.getValue()));
			}
			if(isExtensionAttr != null) {
				dataType.setIsExtension(Boolean.valueOf(isExtensionAttr.getValue()));
			}
			result.add(dataType);
		}
		return result;
	}
}
